package com.wavehi.test;

import com.waveh.mapper.IUserDynamicSQLMapper;
import com.wavehi.pojo.User;
import com.wavehi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * @Author WaveHi
 * @Date 28/9/2021 下午 8:01
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Demonstrate the use of level 2 cache.
 */
public class Level02CacheDemo {
    @Test
    public void userLevel02Cache01() {
        SqlSession session01 = null;
        SqlSession session02 = null;
        try {
            //获取数据库会话
            session01 = MyBatisUtils.getSession();
            session02 = MyBatisUtils.getSession();
            //获取代理对象
            IUserDynamicSQLMapper mapper01 = session01.getMapper(IUserDynamicSQLMapper.class);
            IUserDynamicSQLMapper mapper02 = session02.getMapper(IUserDynamicSQLMapper.class);
            //查询(先去二级缓存查询)
            User user01 = mapper01.selectById(1L);
            if(session01 != null) {
                session01.commit();
            }
            //会从二级缓存中获取数据
            User user02 = mapper02.selectById(1L);
            if(session02 != null) {
                session02.close();
                session02 = null;
            }
            //测试
//            if(user01 == user02) {
//                System.out.println("User01 and user02 is the same object!");
//            }else {
//                System.out.println("User01 and user02 is not the same object!");
//            }
        } finally {
            //资源的关闭
            if(session01 != null) {
                session01.close();
            }
            if(session02 != null) {
                session02.close();
            }
        }
    }
}
